package com.dmy.common.utils.qr_code;

import com.google.zxing.EncodeHintType;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.Data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * create by huahuadelei for 2020/1/5
 */
public class QRCodeConfig {
    private int width = 300;
    private int height = 300;
    private String imgFormat = "png";
    private boolean isLogo = false;
    private QRCodeLogoConfig codeLogoConfig;
    //定义二维码的参数
    private Map<EncodeHintType,Object> hints = new HashMap();
    {
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.MARGIN, 0);
    }

    public Map<EncodeHintType, Object> hints() {
        return hints;
    }
    public QRCodeConfig hint(EncodeHintType type,Object value) {
        this.hints.put(type,value);
        return this;
    }

    public void setHints(Map<EncodeHintType, Object> hints) {
        this.hints = hints;
    }

    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public boolean isLogo() {
        return isLogo;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public String getImgFormat() {
        return imgFormat;
    }

    public void setImgFormat(String imgFormat) {
        this.imgFormat = imgFormat;
    }

    public QRCodeLogoConfig getCodeLogoConfig() {
        return codeLogoConfig;
    }

    public void setCodeLogoConfig(QRCodeLogoConfig codeLogoConfig) {
        if(codeLogoConfig != null){
            isLogo = true;
        }
        this.codeLogoConfig = codeLogoConfig;
    }


    public static class QRCodeLogoConfig{
        private InputStream fileInput;

        private QRCodeLogoConfig(InputStream fileInput) {
            this.fileInput = fileInput;
        }
        private QRCodeLogoConfig(File file) {
            try {
                this.fileInput = new FileInputStream(file);
            } catch (FileNotFoundException e) {
            }
        }

        protected InputStream getLogoStream() {
            return fileInput;
        }

        public static QRCodeLogoConfig fromFile(File file){
            if(file == null || !file.isFile()){
                throw new IllegalArgumentException("parameter 'file' is null or not a file!!");
            }
            return new QRCodeLogoConfig(file);
        }
        public static QRCodeLogoConfig fromFile(InputStream fileInput){
            if(fileInput == null ){
                throw new IllegalArgumentException("parameter 'file' is null or not a file!!");
            }
            return new QRCodeLogoConfig(fileInput);
        }
    }
}
